<template>
  <div class="scene-management">
    <div class="page-header">
      <h2>场景管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="场景名称">
          <el-input v-model="searchForm.sceneName" placeholder="请输入场景名称" clearable />
        </el-form-item>
        <el-form-item label="场景类型">
          <el-select v-model="searchForm.sceneType" placeholder="请选择场景类型" clearable>
            <el-option label="生活专享场景" :value="1" />
            <el-option label="会员专享" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用范围">
          <el-select v-model="searchForm.sceneScope" placeholder="请选择适用范围" clearable>
            <el-option label="所有人" :value="1" />
            <el-option label="会员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="场景状态">
          <el-select v-model="searchForm.sceneState" placeholder="请选择状态" clearable>
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchScenes">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增场景
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="sceneList" v-loading="loading" stripe>
        <el-table-column prop="sceneId" label="场景ID" width="80" />
        <el-table-column prop="sceneName" label="场景名称" width="200" />
        <el-table-column prop="sceneType" label="场景类型" width="150">
          <template #default="{ row }">
            <el-tag :type="row.sceneType === 1 ? 'primary' : 'success'">
              {{ getSceneTypeText(row.sceneType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sceneTime" label="场景时间" width="180" />
        <el-table-column prop="sceneScope" label="适用范围" width="120">
          <template #default="{ row }">
            <el-tag :type="row.sceneScope === 1 ? 'info' : 'warning'">
              {{ getSceneScopeText(row.sceneScope) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sceneState" label="场景状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getSceneStateType(row.sceneState)">
              {{ getSceneStateText(row.sceneState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editScene(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteScene(row.sceneId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑场景' : '新增场景'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="sceneForm" :rules="sceneRules" ref="sceneFormRef" label-width="120px">
        <el-form-item label="场景名称" prop="sceneName">
          <el-input v-model="sceneForm.sceneName" placeholder="请输入场景名称" />
        </el-form-item>
        <el-form-item label="场景类型" prop="sceneType">
          <el-select v-model="sceneForm.sceneType" placeholder="请选择场景类型">
            <el-option label="生活专享场景" :value="1" />
            <el-option label="会员专享" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="场景时间" prop="sceneTime">
          <el-date-picker
            v-model="sceneForm.sceneTime"
            type="datetime"
            placeholder="请选择场景时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="适用范围" prop="sceneScope">
          <el-select v-model="sceneForm.sceneScope" placeholder="请选择适用范围">
            <el-option label="所有人" :value="1" />
            <el-option label="会员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="场景状态" prop="sceneState">
          <el-select v-model="sceneForm.sceneState" placeholder="请选择状态">
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { sceneApi } from '@/api/scene'

// 响应式数据
const loading = ref(false)
const sceneList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const sceneFormRef = ref()

// 搜索表单
const searchForm = reactive({
  sceneName: '',
  sceneType: null,
  sceneScope: null,
  sceneState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 场景表单
const sceneForm = reactive({
  sceneId: null,
  sceneName: '',
  sceneType: null,
  sceneTime: '',
  sceneScope: null,
  sceneState: 1
})

// 表单验证规则
const sceneRules = {
  sceneName: [
    { required: true, message: '请输入场景名称', trigger: 'blur' }
  ],
  sceneType: [
    { required: true, message: '请选择场景类型', trigger: 'change' }
  ],
  sceneTime: [
    { required: true, message: '请选择场景时间', trigger: 'change' }
  ],
  sceneScope: [
    { required: true, message: '请选择适用范围', trigger: 'change' }
  ],
  sceneState: [
    { required: true, message: '请选择场景状态', trigger: 'change' }
  ]
}

// 获取场景类型文本
const getSceneTypeText = (type) => {
  const typeMap = {
    1: '生活专享场景',
    2: '会员专享'
  }
  return typeMap[type] || '未知'
}

// 获取适用范围文本
const getSceneScopeText = (scope) => {
  const scopeMap = {
    1: '所有人',
    2: '会员'
  }
  return scopeMap[scope] || '未知'
}

// 获取场景状态文本
const getSceneStateText = (state) => {
  const stateMap = {
    1: '进行中',
    2: '已终止'
  }
  return stateMap[state] || '未知'
}

// 获取场景状态标签类型
const getSceneStateType = (state) => {
  const stateMap = {
    1: 'success',
    2: 'danger'
  }
  return stateMap[state] || 'info'
}

// 搜索场景
const searchScenes = async () => {
  loading.value = true
  try {
    const response = await sceneApi.getSceneList(searchForm)
    if (response.code === 200) {
      sceneList.value = response.data || []
      pagination.total = sceneList.value.length
    }
  } catch (error) {
    console.error('搜索场景失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    sceneName: '',
    sceneType: null,
    sceneScope: null,
    sceneState: null
  })
  searchScenes()
}

// 编辑场景
const editScene = (row) => {
  isEdit.value = true
  Object.assign(sceneForm, row)
  showAddDialog.value = true
}

// 删除场景
const deleteScene = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个场景吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await sceneApi.deleteScene(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchScenes()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除场景失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await sceneFormRef.value.validate()

    const response = isEdit.value
      ? await sceneApi.updateScene(sceneForm)
      : await sceneApi.addScene(sceneForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchScenes()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(sceneForm, {
    sceneId: null,
    sceneName: '',
    sceneType: null,
    sceneTime: '',
    sceneScope: null,
    sceneState: 1
  })
  isEdit.value = false
  sceneFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchScenes()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchScenes()
}

// 初始化
onMounted(() => {
  searchScenes()
})
</script>

<style scoped>
.scene-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>


